<template>
    <van-popup :show="show" position="bottom" round :style="{ height: '60%' }">
        <div class="interview-confirm">

            <!-- 已登录状态 -->
            <div class="header">
                <div class="title">确认面试信息</div>
                <van-icon name="cross" @click="handleClose" />
            </div>

            <div class="content">
                <!-- 面试简历 -->
                <div class="section">
                    <div class="section-header">
                        <span class="label">面试简历</span>
                        <div class="action" @click="handleEditResume">
                            <span>去修改</span>
                            <van-icon name="arrow" />
                        </div>
                    </div>
                    <div class="resume-card">
                        <van-icon name="description" />
                        <span class="file-name">{{ resumeInfo?.name || '未选择简历' }}</span>
                    </div>
                </div>

                <!-- 面试职位 -->
                <div class="section">
                    <div class="section-header">
                        <span class="label">面试职位</span>
                        <div class="action" @click="handleEditJob">
                            <span>去修改</span>
                            <van-icon name="arrow" />
                        </div>
                    </div>
                    <div class="job-card">
                        <span class="job-name">{{ jobInfo?.name || '未选择职位' }}</span>
                    </div>
                </div>
            </div>

            <!-- 底部按钮 -->
            <div class="footer">
                <van-button type="primary" block :disabled="!canStart" v-loading="handleStart">
                    立即面试
                </van-button>
            </div>
        </div>
    </van-popup>
</template>

<script setup>
    import { ref, computed, watch } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
    import { useInterviewStore } from '@/store/modules/interview'
    import { useUserStore } from '@/store/modules/user'
    import { resumeApi } from '@/api/resume'
    import { jobApi } from '@/api/job'
    import { interviewApi } from '@/api/interview'
    import { showToast } from 'vant'
    import emitter from '@/utils/eventBus'

    const props = defineProps({
        show: Boolean
    })

    const emit = defineEmits(['update:show'])
    const router = useRouter()
    const route = useRoute()
    const interviewStore = useInterviewStore()
    const userStore = useUserStore()

    // 简历和职位信息
    const resumeInfo = ref(null)
    const jobInfo = ref(null)

    // 是否可以开始面试
    const canStart = computed(() => {
        return !!(resumeInfo.value && jobInfo.value)
    })

    // 获取默认简历和岗位
    const fetchDefaultInfo = async () => {
        try {
            const [resumeRes, jobRes] = await Promise.all([
                resumeApi.getDefaultResume(),
                jobApi.getDefaultJob()
            ])

            if (resumeRes.data) {
                resumeInfo.value = {
                    id: resumeRes.data[0].id,
                    name: resumeRes.data[0].cv_name
                }
            }

            if (jobRes.data) {
                jobInfo.value = {
                    id: jobRes.data[0].id,
                    name: jobRes.data[0].jd_title
                }
            }
        } catch (error) {
            console.error('获取默认信息失败:', error)
        }
    }

    // 关闭弹窗
    const handleClose = () => {
        emit('update:show', false)
    }

    // 编辑简历
    const handleEditResume = () => {
        sessionStorage.setItem('interviewConfirmPreviousRoute', route.fullPath)
        router.push('/profile/resume')
    }

    // 编辑职位
    const handleEditJob = () => {
        sessionStorage.setItem('interviewConfirmPreviousRoute', route.fullPath)
        router.push('/profile/jobs')
    }

    // 开始面试
    const handleStart = async () => {
        try {

            if (!resumeInfo.value || !jobInfo.value) {
                showToast('请先选择简历和职位')
                return
            }

            // 创建面试
            const res = await interviewApi.createInit({
                cv_id: resumeInfo.value.id,
                jd_id: jobInfo.value.id
            })

            if (res.data?.interview_record_id) {
                router.push({
                    path: '/interview/voice',
                    query: {
                        interview_record_id: res.data.interview_record_id
                    }
                })
                handleClose()
            } else {
                showToast('创建面试失败')
            }
        } catch (error) {
            console.error('开始面试失败:', error)
            let message = error.response.data.msg;
            showToast(message || '开始面试失败,请重试')
        }
    }

    // 监听弹窗显示状态
    watch(() => props.show, (newVal) => {
        if (newVal) {
            fetchDefaultInfo()
        }
    })

    // 监听简历和职位更新事件
    const handleUpdateInfo = (item) => {
        console.log('收到更新数据:', item)
        if (item.cv_name) {
            // 更新简历信息
            resumeInfo.value = {
                id: item.id,
                name: item.cv_name
            }
        } else if (item.jd_title) {
            // 更新职位信息
            jobInfo.value = {
                id: item.id,
                name: item.jd_title
            }
        }
    }

    onMounted(() => {
        emitter.on('update-info-status', handleUpdateInfo)
        console.log('InterviewConfirm组件挂载，添加事件监听')
    })

    // 组件卸载前移除事件监听
    onBeforeUnmount(() => {
        emitter.off('update-info-status', handleUpdateInfo)
        console.log('InterviewConfirm组件卸载，移除事件监听')
    })
</script>

<style lang="scss" scoped>
    .interview-confirm {
        height: 100%;
        display: flex;
        flex-direction: column;
        padding: 20px;

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;

            .title {
                font-size: 18px;
                font-weight: 500;
                color: #333;
            }

            .van-icon {
                font-size: 20px;
                color: #999;
                cursor: pointer;
            }
        }

        .content {
            flex: 1;
            overflow-y: auto;

            .section {
                margin-bottom: 24px;

                .section-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 12px;

                    .label {
                        font-size: 16px;
                        color: #333;
                    }

                    .action {
                        display: flex;
                        align-items: center;
                        color: rgba(134, 144, 156, 1);
                        cursor: pointer;

                        span {
                            font-size: 14px;
                            margin-right: 4px;
                        }
                    }
                }

                .resume-card,
                .job-card {
                    padding: 16px;
                    background: #f5f6f7;
                    border-radius: 8px;
                    display: flex;
                    align-items: center;

                    .van-icon {
                        font-size: 20px;
                        color: rgba(29, 33, 41, 1);
                        margin-right: 8px;
                    }

                    .file-name,
                    .job-name {
                        color: #333;
                        font-size: 14px;
                    }
                }
            }
        }

        .footer {
            padding-top: 16px;

            .van-button {
                height: 44px;
                border-radius: 22px;
                background: #8a2be2;
                border: none;
                font-size: 16px;

                &--disabled {
                    background: #ccc;
                }
            }
        }

        .login-tip {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 40px 0;

            .avatar {
                width: 120px;
                height: 120px;
                border-radius: 50%;
                margin-bottom: 20px;
            }

            .tip-text {
                font-size: 18px;
                color: #333;
                font-weight: 500;
            }
        }
    }
</style>